<script setup lang="ts">
import router from '@/router'
import { createOrder, getConsultOrderPre } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onMounted } from 'vue'
import { ref } from 'vue'
// import { useRouter } from 'vue-router'
import { onBeforeRouteLeave } from 'vue-router'

/* 
  一旦创建好订单后 不允许用户离开当前页面

  全局守卫
  路由独享守卫
  组件内的守卫 onBeforeRouteLeave(() => { 一旦离开页面 就会触发 })
*/

onBeforeRouteLeave(() => {
  // console.log(111)
  if (orderId.value) return false // 订单存在时 不执行任何返回操作
})

const store = useConsultStore()

// 折扣信息数据
const payInfo = ref<ConsultOrderPreData>()
const loadData = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type, // 开药问诊 极速问诊 找医生
    illnessType: store.consult.illnessType // 三甲 普通
  })
  payInfo.value = res.data

  // 设置默认优惠券(这是我们一会创建订单的最后一个数据)
  store.setCoupon(payInfo.value.couponId)
}

const patient = ref<Patient>()
const loadPatient = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetail(store.consult.patientId)
  patient.value = res.data
}

type Key = keyof PartialConsult
onMounted(() => {
  // 先做判断有无清空仓库

  const validKeys: Key[] = [
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId'
  ]
  const valid = validKeys.every((key) => store.consult[key] !== undefined)
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }

  // 数据还在 请求折扣信息 病患信息
  loadData()
  loadPatient()
})

/* 
  1. 获取折扣信息(存了一个优惠券id)
  2. 获取患者信息
*/

const agree = ref(false) // 我同意
const show = ref(false) // 打开支付方式

const orderId = ref('')
const loading = ref(false)
const fn = async () => {
  // console.log(111)
  if (!agree.value) return showToast('你同不同意')

  loading.value = true
  const res = await createOrder(store.consult)
  orderId.value = res.data.id

  loading.value = false
  // 创建好订单了 那么store.consult就应该清空了
  store.clear()

  // 选择支付之前 先创建订单
  show.value = true
}

// 纯数字 => 枚举
// const paymentMethod = ref<0 | 1>()

// const pay = async () => {
//   if (paymentMethod.value === undefined) return showToast('你选一个支付方式')

//   const res = await getPayURL({
//     paymentMethod: paymentMethod.value, // 支付方式
//     orderId: orderId.value, // 订单id
//     payCallback: 'http://127.0.0.1:5173/room' // 支付完成后的跳转回项目的地址
//   })
//   console.log(res.data.payUrl)

//   location.href = res.data.payUrl // 跳转支付宝
// }

// const router = useRouter()
const beforeClose = () => {
  // return false // 阻止关闭
  /* 
    创建好订单了, 进入到支付环节
      1. 直接在当前页面完成支付流程
      2. 直接放弃支付 等会去订单页面找到这笔未支付订单完成支付
  */
  // return false
  // 因为确认框的选择结果会影响当前这个弹窗是否关闭
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付'
  })
    .then(() => {
      console.log('继续支付')
      // 不关闭弹窗
      return false
    })
    .catch(() => {
      console.log('仍要关闭')

      orderId.value = '' // 保证能离开当前页面
      router.push('/user/consult')
      // 关闭
      return true
    })

  // return undefined
}
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo && patient">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @submit="fn"
      :loading="loading"
    />

    <!-- 
      close-on-popstate 默认值是true 返回时会自动关闭
                               false  返回是不自动关闭
      closeable 显示关闭图标
      before-close 是个函数 return false 表示不关闭
     -->
    <cp-pay-sheet
      v-model:show="show"
      :order-id="orderId"
      :actualPayment="payInfo.actualPayment"
      :onClose="beforeClose"
      payCallback="/room"
    />
    <!-- <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      :closeable="false"
      :before-close="beforeClose"
    >
      <div class="pay-type">
        <p class="amount">￥ {{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell @click="paymentMethod = 0" title="微信支付">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 0" />
            </template>
          </van-cell>
          <van-cell @click="paymentMethod = 1" title="支付宝支付">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 1" />
            </template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet> -->
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
